<?php

namespace plugin\admin\app\controller;

use app\services\UserCouponService;
use app\traits\DataProcessor;
use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\GoodsCategory;
use support\Db;
use support\Request;
use support\Response;
use plugin\admin\app\model\Coupon;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 优惠券 
 */
class CouponController extends Crud
{
    
    /**
     * @var Coupon
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Coupon;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('coupon/index');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

//        DataProcessor::processSwitch($data, ['only_for_gift']);

        $this->check($data);

        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('coupon/insert');
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        $this->check($data);

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('coupon/update');
    }

    public function check(&$data)
    {
        if (isset($data['type'])) {
            if ($data['type'] == Coupon::TYPE_ANYWAY) {
                $data['full'] = bcadd($data['reduce'], 0.00, 2);
            } else {
                if ($data['full'] <= $data['reduce']) {
                    throw new \Exception('门槛金额不能小于等于减免金额');
                }
            }
        }

    }

    public function give(Request $request)
    {
        if ($request->isAjax() && $request->method() == 'POST') {

            Db::beginTransaction();
            try {
                UserCouponService::give($request->post('coupon_id'), $request->post('user_id'));
                Db::commit();
                return $this->json(0, '成功');
            } catch (\Exception $e) {
                Db::rollBack();
                return $this->json(400, $e->getMessage());
            }
        }

        return view('coupon/give', [
            'id' => $request->get('id')
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isAjax() && $request->method() == 'POST') {

            Db::beginTransaction();
            try {
                UserCouponService::give($request->post('id'), $request->post('third_party_id'));
                Db::commit();
                return $this->json(0, '成功');
            } catch (\Exception $e) {
                Db::rollBack();
                return $this->json(400, $e->getMessage());
            }
        }
    }

    protected function formatNormal($items, $total): Response
    {
        $categoryIdsList = array_filter(array_column($items, 'goods_category_ids'));
        $categoryIds = explode(',', join(',', $categoryIdsList));

        $categories = GoodsCategory::whereIn('id', $categoryIds)->get()->toArray();
        $categories = array_combine(
            array_column($categories, 'id'),
            array_values($categories)
        );

        foreach ($items as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $item['type_text'] = Coupon::getTypeText($item['type']);
            $item['total_count_text'] = Coupon::getTotalCountText($item['total_count']);

            $item['goods_category_names'] = [];

            foreach (array_filter(explode(',', $item['goods_category_ids'])) ?? [] as $categoryId) {
                $item['goods_category_names'][] = $categories[$categoryId]['name'];
            }

            if (count($item['goods_category_names']) == 0) {
                $item['goods_category_names'] = '所有品类';
            } else {
                $item['goods_category_names'] = join(',', $item['goods_category_names']);
            }

            $items[$key] = $item;
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
